﻿using System;
using System.Collections.Generic;
using System.IO;
using WcfFlashRemoting.IO;
using WcfFlashRemoting.AmfObjects;

namespace WcfFlashRemoting.IO
{
    class AmfWriter : IDisposable
    {
        BinaryWriter writer;

        public AmfWriter(Stream output)
        {
            writer = new BigEndianBinaryWriter(output);
        }

        public void WriteAmfMessage(AmfMessage resultMessage)
        {
            Writers.AmfBaseWriter amfWriter;
            writer.Write(resultMessage.Version);

            switch (resultMessage.Version)
            {
                case 0:
                    amfWriter = new Writers.Amf0Writer(writer);
                    break;
                case 3:
                    amfWriter = new Writers.Amf3Writer(writer);
                    break;
                default:
                    throw new InvalidOperationException();
            }
            amfWriter.WriteAmfMessage(resultMessage);

            writer.Flush();
        }


        #region IDisposable Members

        public void Dispose()
        {
            if (writer != null)
            {
                writer.Flush();
                (writer as IDisposable).Dispose();
                writer = null;
            }
        }

        #endregion

    }
}
